package com.boot.study.config;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.SingleKeyTableShardingAlgorithm;
import com.google.common.collect.Range;

/**
* @Title:
* @Description: 表路由规则
* @author chenchen
* @date 2018/8/6 15:29
*/
public class ModuloTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Long> {

	/**
	 * orderId = ?
	 */
	@Override
	public String doEqualSharding(Collection<String> availableTargetNames, ShardingValue<Long> shardingValue) {
		String value = "_" + shardingValue.getValue() % 3;
		for (String str : availableTargetNames) {// t_order_0,t_order_1,t_order_2
			if (str.endsWith(value)) {
				return str;
			}
		}
		throw new RuntimeException("未找到相应表");
	}

	/**
	 * orderId in ()
	 */
	@Override
	public Collection<String> doInSharding(Collection<String> availableTargetNames, ShardingValue<Long> shardingValue) {
		Set<String> names = new HashSet<>();
		shardingValue.getValues().forEach(orderId -> {
			String value = "_" + orderId % 3;
			for (String str : availableTargetNames) {// t_order_0,t_order_1,t_order_2
				if (str.endsWith(value)) {
					names.add(str);
				}
			}
		});
		return names;
	}

	@Override
	public Collection<String> doBetweenSharding(Collection<String> availableTargetNames,
			ShardingValue<Long> shardingValue) {
		Set<String> names = new HashSet<>();
		Range<Long> range = shardingValue.getValueRange();
		for (Long orderId = range.lowerEndpoint(); orderId <= range.upperEndpoint(); orderId++) {
			String value = "_" + orderId % 3;
			for (String str : availableTargetNames) {// t_order_0,t_order_1,t_order_2
				if (str.endsWith(value)) {
					names.add(str);
				}
			}
		}
		return names;
	}

}
